package com.github.niefy.modules.wx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.niefy.common.utils.PageUtils;
import com.github.niefy.common.utils.Query;
import com.github.niefy.modules.wx.dao.SubMsgTemplateMapper;
import com.github.niefy.modules.wx.entity.SubMsgTemplate;
import com.github.niefy.modules.wx.service.SubMsgTemplateService;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class SubMsgTemplateServiceImpl extends ServiceImpl<SubMsgTemplateMapper, SubMsgTemplate> implements SubMsgTemplateService {

    private WxMpService wxService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String title = (String) params.get("title");
        String name = (String) params.get("name");
        String appid = (String) params.get("appid");
        IPage<SubMsgTemplate> page = this.page(
            new Query<SubMsgTemplate>().getPage(params),
            new QueryWrapper<SubMsgTemplate>()
                .eq(StringUtils.hasText(appid), "appid", appid)
                .like(StringUtils.hasText(title), "title", title)
                .like(StringUtils.hasText(name), "name", name)
        );

        return new PageUtils(page);
    }

    @Override
    public SubMsgTemplate selectByName(String name) {
        Assert.hasText(name, "模板名称不得为空");
        return this.getOne(new QueryWrapper<SubMsgTemplate>()
            .eq("name", name)
            .eq("status", 1)
            .last("LIMIT 1"));
    }

    @Override
    public void syncWxSubTemplate(String appid) throws WxErrorException {
        var templateList = wxService.getSubscribeMsgService().getTemplateList();
        List<SubMsgTemplate> templates = templateList.stream().map(item->new SubMsgTemplate(item,appid)).collect(Collectors.toList());
        //先清空，后新增
        this.remove((new QueryWrapper<SubMsgTemplate>()).eq("appid", appid));
        this.saveBatch(templates);
    }

}
